/**
 * There are code generation
 */
package com.neusoft.lohas.modules.ivm.web.merchant;

import org.apache.shiro.authz.annotation.RequiresUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.neusoft.lohas.common.config.Global;
import com.neusoft.lohas.common.utils.StringUtils;
import com.neusoft.lohas.common.web.BaseController;
import com.neusoft.lohas.modules.ivm.entity.merchant.Merchant;
import com.neusoft.lohas.modules.ivm.service.merchant.MerchantService;
import com.neusoft.lohas.modules.ivm.utils.MerchantUtils;
import com.neusoft.lohas.modules.sys.utils.UserUtils;

/**
 * 商户Controller
 * @author Jackie.Liu
 * @version 2014-10-22
 */
@Controller
@RequestMapping(value = "${adminPath}/ivm/merchant")
public class MerchantController extends BaseController {

	@Autowired
	private MerchantService merchantService;
	
	@ModelAttribute
	public Merchant get(@RequestParam(required=false) String id) {
		if (StringUtils.isNotBlank(id)){
			return merchantService.get(id);
		}else{
			return new Merchant();
		}
	}
	
	@RequiresUser
	@RequestMapping(value = "set")
	public String set(Merchant merchant, Model model) {
		return "modules/ivm/set/setIndex";
	}
	
	@RequiresUser
	@RequestMapping(value = "info")
	public String info(Merchant merchant, Model model) {
		Merchant currentMerchant = MerchantUtils.getMerchant();
		if (StringUtils.isNotBlank(merchant.getName())){
			if(Global.isDemoMode()){
				model.addAttribute("message", "演示模式，不允许操作！");
				return "modules/ivm/merchantInfo";
			}
			merchantService.save(merchant);
			model.addAttribute("message", "保存商户信息成功");
			currentMerchant = merchantService.findByCreateBy(UserUtils.getUser().getId());
			MerchantUtils.putCache(MerchantUtils.CACHE_MERCHANT, currentMerchant);
		}
		if (StringUtils.isNotBlank(merchant.getId()) && StringUtils.isBlank(merchant.getShopUrl())) {
			merchant.setShopUrl(frontPath+"?sid="+merchant.getId()+"&shopModel=merchant");
			//第一次保存，生成手机端电商商户主页链接
			merchantService.save(merchant);
			currentMerchant = merchantService.findByCreateBy(UserUtils.getUser().getId());
			MerchantUtils.putCache(MerchantUtils.CACHE_MERCHANT, currentMerchant);
		}
		if (StringUtils.isNotBlank(currentMerchant.getShopUrl()) && currentMerchant.getShopUrl().indexOf("shopModel")==-1) {
			currentMerchant.setShopUrl(currentMerchant.getShopUrl()+"&shopModel=merchant");
			MerchantUtils.putCache(MerchantUtils.CACHE_MERCHANT, currentMerchant);
		}
		model.addAttribute("merchant", currentMerchant);
		return "modules/ivm/merchantInfo";
	}

}
